﻿<form id="frmBXJGShopCustomer">
    <input type="hidden" name="id" value="0" />
    <input type="hidden" name="userId" value="0" />
    <table class="frm-box">
        <tr>
            <th>姓名</th>
            <td>
                <input name="name" class="easyui-textbox" data-options="required:true, validType:'length[2,20]'" />
            </td>
            <th>性别</th>
            <td>
                <input name="gender" class="easyui-switchbutton" data-value-type="number" value="2" data-unchecked-value="1" data-options="offText:'男',onText:'女'" />
            </td>
        </tr>
        <tr>
            <th>出生日期</th>
            <td>
                <input name="birthday" class="easyui-datebox" />
            </td>
            <th>手机号</th>
            <td><input name="phoneNumber" class="easyui-textbox" data-options="required:true, validType:'phone'" /></td>
        </tr>
        <tr>
            <th>邮箱</th>
            <td><input name="emailAddress" class="easyui-textbox" data-options="required:true, validType:'email'" /></td>

            <th>区域</th>
            <td>
                <input name="areaId" class="easyui-combotree" data-options="editable:false, url:abp.appPath+ 'api/services/app/BXJGBaseInfoAdministrative/getTreeForSelect',queryParams: {forType: 4}" />
            </td>
        </tr>
        <tr>
            <th class="top">收货地址</th>
            <td colspan="3" style="padding:5px 0;" id="BXJGShopCustomerAddr">
                <table class="dgShippingAddreses"></table>
            </td>
        </tr>
        <tr>
            <th>登录名</th>
            <td><input name="userName" class="easyui-textbox" data-options="required:true, validType:'length[0,50]'" /></td>
            <th>激活</th>
            <td><input type="checkbox" name="isActive" class="easyui-switchbutton" value="true" checked data-unchecked-value="false" /></td>
        </tr>
        <tr>
            <th>密码</th>
            <td><input name="password" type="password" autocomplete="off" class="easyui-textbox" data-options="required:true, iconCls:'icon-lock'" /></td>
            <th>密码确认</th>
            <td><input name="passwordConfirm" type="password" autocomplete="off" class="easyui-textbox" data-options="required:true, iconCls:'icon-lock'" validType="passwordEquals['#frmBXJGShopCustomer input[name=\'password\']']" /></td>
        </tr>
    </table>
</form>

<script>



    (function () {
        //一对dom对应的jq对象
        const m = 'BXJGShopCustomer';
        const $dlg = $('#dlg' + m);
        const $frm = $dlg.find('form');
        const id = $dlg.data('id');
        const $name = $frm.find('[name="name"]');
        //const $area = $frm.find('[name="areaId"]');
        //const $showHide = $frm.find('.showhide');
        const $userName = $frm.find('[name="userName"]');
        const $password = $frm.find('[name="password"]');
        const $passwordConfirm = $frm.find('[name="passwordConfirm"]');
        const $dgShippingAddreses = $frm.find('.dgShippingAddreses');

        //此处确保easyui控件已初始化完成
        setTimeout(function () {
            $name.next('span').find('input').focus();
            abp.easyui.serializejsonSwitchbutton($frm);
        }, 0);

        //存储区域数据
        let areas;
        //初始化区域数据的异步任务
        let initArea = abp.services.app.bXJGBaseInfoAdministrative.getTreeForSelect({ forType: 4 }).done(function (d) {
            areas = d;
        });

        //递归区域树，根据id找文本
        function recursionArea(val, as) {
            if (!val)
                return null;

            for (let i = 0; i < as.length; i++) {
                let item = as[i];
                if (item.id == val) {
                    return item.text;
                }
                if (item.children) {
                    let txt = recursionArea(val, item.children)
                    if (txt)
                        return txt;
                }
            }
        }
        //function clearRow(index) {
        //    ;

        //}
        //初始化地址列表
        let currIndex = 0;
        let initAddress = $.when(initArea/*,依赖的其它异步写这里*/).done(function () {

            $dgShippingAddreses.datagrid({
                width: 750,
                height: 280,
                singleSelect: true,
                rownumbers: true,
                //toolbar: [{
                //    iconCls: 'icon-add',
                //    text: '添加',
                //    handler: function () {
                //        alert('edit')
                //    }
                //}],
                columns: [[
                    {
                        field: 'btns', title: '操作', width: 50, align: 'center',
                        formatter: function (value, row, index) {
                            if (row.name || row.phone || row.areaId || row.address)
                                return '<a href="javascript:void(0);">清空</a>';
                            return '';
                            // onclick="$dgShippingAddreses.datagrid(\'updateRow\', { index: ' + index + ',  row: {} })
                        }
                    },
                    {
                        field: 'isDefault', title: '默认', width: 50, align: 'center',
                        editor: {
                            type: 'checkbox',
                            options: {
                                on: "true",
                                off: ""//,×
                            }
                        },
                        formatter: abp.easyui.datagridBool
                    },
                    {
                        field: 'name', title: '姓名', width: 80,
                        editor: {
                            type: 'textbox',
                            options: {
                                //required: true
                            }
                        }
                    },
                    {
                        field: 'phone', title: '电话', width: 120,
                        editor: {
                            type: 'textbox',
                            options: {
                                //required: true
                            }
                        }
                    },
                    {
                        field: 'areaId', title: '区域', width: 150, editor: {
                            type: 'combotree',
                            options: {
                                editable: true,
                                data: areas,
                                queryParams: { forType: 4 }
                                //,required: true
                            }
                        },
                        formatter: function (value, row, index) {
                            return recursionArea(value, areas);
                        }
                    },
                    { field: 'address', title: '地址', width: 250, editor: 'textbox' },
                    { field: 'zipCode', title: '邮编', width: 80, editor: 'textbox' }
                ]],
                onSelect: function (index, row) {
                    //console.log($dgShippingAddreses.datagrid('validateRow', currIndex));
                    //if (!$dgShippingAddreses.datagrid('validateRow', currIndex)) {
                    //    return;
                    //}
                    $dgShippingAddreses.datagrid('endEdit', currIndex);
                    $dgShippingAddreses.datagrid('beginEdit', index);
                    currIndex = index;
                },
                onClickCell: function (index, field, value) {
                    if (field == 'btns') {
                        let rows = $dgShippingAddreses.datagrid('getRows');
                        for (let i = 0; i < rows.length; i++) {
                            if (i === index) {
                                let row = rows[i];
                                for (let p in row) {
                                    row[p] = '';
                                }
                                $dgShippingAddreses.datagrid('refreshRow', i);
                            }
                        }
                    }
                    //$dgShippingAddreses.datagrid('updateRow', { index: index, row: { name:'' } });
                },
                //onEndEdit: function (index, row, changes) {
                //    if (!$dgShippingAddreses.datagrid('validateRow', index)) {
                //        return false;
                //    }
                //},
                onAfterEdit: function (index, row, changes) {
                    let rows = $dgShippingAddreses.datagrid('getRows');
                    if (row.isDefault) {
                        for (let i = 0; i < rows.length; i++) {
                            if (index === i) {
                                continue;
                            }
                            let item = rows[i];
                            item.isDefault = false;
                            $dgShippingAddreses.datagrid('refreshRow', i);
                        }
                    } else {
                        row.isDefault = true;
                        for (let i = 0; i < rows.length; i++) {
                            if (index === i) {
                                continue;
                            }
                            if (rows[i].isDefault) {
                                //console.log(i);
                                row.isDefault = false;
                                $dgShippingAddreses.datagrid('refreshRow', index);
                                return;
                            }
                        }
                    }
                }

                //,onLoadSuccess: function (data) {
                //    $("a[name='opera']").linkbutton({
                //        text: '清空', plain: true, iconCls1: 'icon-add', onClick: function () {
                //            console.log(this);
                //        }
                //    });
                //}
            });
            //$dgShippingAddreses.datagrid('options').view.onAfterRender = function (target) {
            //    console.log(target);
            //$.parser.parse(target);
            //};
            for (let i = 0; i < 30; i++) {
                $dgShippingAddreses.datagrid('appendRow', {});
            }

            //$.parser.parse('#frmBXJGShopCustomer');
            $dgShippingAddreses.datagrid('beginEdit', 0);
        });

        //点击保存按钮并处理完成后的回调
        function onSaved(funcName) {
            var f = $dlg.data(funcName);
            if (f)
                f();
        }
        //点击保存按钮的回调
        $dlg.data('clickSave', function () {
            //表单验证
            if (!$frm.form('validate'))
                return;

            //表单序列化为json，准备提交
            let postData = $frm.serializeJSON();

            //let notValide = false;
            postData.shippingAddresses = new Array();

            $dgShippingAddreses.datagrid('endEdit', currIndex);
            let notValid = false;
            let addrRows = $dgShippingAddreses.datagrid('getRows');
            for (let i = 0; i < addrRows.length; i++) {
                let row = addrRows[i];
                if (row.name && row.phone && row.areaId && row.address) {
                    postData.shippingAddresses.push(row);
                } else {
                    notValid = true;
                    continue;
                }
            }



            if (notValid) {
                abp.notify.warn('收货地址名称、电话、区域、地址必须输入，不符合条件将被忽略.');
            }

            let defer;
            if (id) {
                if ($password.val() != $passwordConfirm.val()) {
                    abp.message.error('密码确认不一致！', '输入验证');
                    return;
                }
                defer = abp.services.app.bXJGShopCustomer.update(postData).done(function (d) {
                    abp.notify.success(abp.localization.zlj('Update') + abp.localization.zlj('Success') + '!');
                    //abp.message.info("sf");
                    onSaved('onUpdated');
                });
            } else {
                defer = abp.services.app.bXJGShopCustomer.create(postData).done(function (d) {
                    abp.notify.success(abp.localization.zlj('Add') + abp.localization.zlj('Success') + '!');
                    onSaved('onAdded');
                });
            }
            abp.ui.setBusy($dlg, defer);


        });

        //初始化加载表单数据对象并赋值控件
        if (id) {
            let initFrm = abp.services.app.bXJGShopCustomer.get({ id: id }).done(function (d) {
                $frm.form('load', d);
                if (d.shippingAddresses) {
                    initAddress.done(function () {
                        let olds = $dgShippingAddreses.datagrid('getRows');
                        for (let i = 0; i < d.shippingAddresses.length; i++) {
                            let item = d.shippingAddresses[i];
                            let old = olds[i];
                            for (let p in item) {
                                old[p] = item[p];
                            }
                            if (old.isDefault)
                                old.isDefault = 'true'; //'√';
                            $dgShippingAddreses.datagrid('refreshRow', i);
                        }
                        //$.parser.parse('#BXJGShopCustomerAddr');
                        $dgShippingAddreses.datagrid('beginEdit', 0);
                        //$dgShippingAddreses.datagrid('loadData', { total: d.shippingAddresses.length, rows: d.shippingAddresses });
                    });
                }

                //$userName.textbox('readonly',true);
                //$password.textbox('setValue','');
                //$passwordConfirm.textbox('clear');
                $userName.textbox('disableValidation');
                $password.textbox('disableValidation');
                $passwordConfirm.textbox('disableValidation');
            });

            abp.ui.setBusy($dlg, initFrm);
        } else {
            //$showHide.hide();
            //setTimeout(function () {
            //$userName.validatebox('disableValidation');
            //$password.validatebox('disableValidation');
            //$passwordConfirm.validatebox('disableValidation');
            //上面的方式不行
            //$userName.textbox('disable');
            //$password.textbox('disable');
            //$passwordConfirm.textbox('disable');
            //}, 0);
        }
    })();
</script>
